<template>
  <div class="user-posts">
    <div class="header">
      <h2>我的帖子</h2>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        发布新帖
      </el-button>
    </div>

    <!-- 搜索表单 -->
    <el-form :model="searchForm" inline class="search-form">
      <el-form-item label="状态">
        <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
          <el-option label="草稿" value="draft" />
          <el-option label="已发布" value="published" />
          <el-option label="已隐藏" value="hidden" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 帖子表格 -->
    <el-table :data="posts" v-loading="loading" border>
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column prop="title" label="标题" min-width="200" />
      <el-table-column prop="status_display" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusTagType(row.status)">
            {{ row.status_display }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="comments_count" label="评论数" width="80" />
      <el-table-column prop="created_at" label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatDateTime(row.created_at) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button size="small" @click="handleView(row)">查看</el-button>
          <el-button size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 帖子编辑对话框 -->
    <el-dialog
      v-model="showEditModal"
      :title="isAdd ? '发布新帖' : '编辑帖子'"
      width="800px"
      :before-close="handleCloseEdit"
    >
      <el-form ref="postFormRef" :model="postForm" :rules="postRules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="postForm.title" placeholder="请输入帖子标题" />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <RichTextEditor v-model="postForm.content" :height="300" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="postForm.status" placeholder="请选择状态">
            <el-option 
              v-for="option in statusOptions" 
              :key="option.value" 
              :label="option.label" 
              :value="option.value" 
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleCloseEdit">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="isSubmitting">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import request from '@/api/request'
import RichTextEditor from '@/components/RichTextEditor.vue'
import { formatDateTime } from '@/utils'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()

const loading = ref(false)
const showEditModal = ref(false)
const isAdd = ref(true)
const isSubmitting = ref(false)
const postFormRef = ref()

// 动态状态选项
const statusOptions = computed(() => {
  // 管理员可以看到所有状态
  if (userStore.isAdmin) {
    return [
      { label: '草稿', value: 'draft' },
      { label: '发布', value: 'published' },
      { label: '已隐藏', value: 'hidden' },
      { label: '审核中', value: 'review' },
      { label: '已删除', value: 'deleted' },
      { label: '已锁定', value: 'locked' },
      { label: '已封禁', value: 'banned' }
    ]
  }
  // 普通用户只能看到草稿和发布两种状态
  return [
    { label: '草稿', value: 'draft' },
    { label: '发布', value: 'published' }
  ]
})

const searchForm = reactive({
  status: ''
})

const postForm = reactive({
  id: undefined as number | undefined,
  title: '',
  content: '',
  status: 'draft'
})

const posts = ref<any[]>([])

const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

const postRules = {
  title: [{ required: true, message: '请输入帖子标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入帖子内容', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  switch (status) {
    case 'published':
      return 'success'
    case 'draft':
      return 'info'
    case 'hidden':
      return 'warning'
    default:
      return 'info'
  }
}



// 获取帖子列表（只获取当前用户发布的）
const fetchPosts = async (page = 1) => {
  loading.value = true
  try {
    const params: any = {
      page: page,
      page_size: pagination.size,
      // 只获取当前用户发布的帖子
      my_posts: true
    }
    
    if (searchForm.status) {
      params.status = searchForm.status
    }
    
    const response: any = await request.get('/health/posts/', { params })
    posts.value = response.results || []
    pagination.total = response.count || 0
  } catch (error) {
    ElMessage.error('获取帖子列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchPosts()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, { status: '' })
  pagination.current = 1
  fetchPosts()
}

// 查看帖子
const handleView = (row: any) => {
  // 导航到帖子详情页
  router.push(`/posts/${row.id}`)
}

// 新增帖子
const handleAdd = () => {
  isAdd.value = true
  Object.assign(postForm, {
    id: undefined,
    title: '',
    content: '',
    status: 'draft'
  })
  showEditModal.value = true
}

// 编辑帖子
const handleEdit = (row: any) => {
  isAdd.value = false
  Object.assign(postForm, {
    id: row.id,
    title: row.title,
    content: row.content,
    status: row.status
  })
  showEditModal.value = true
}

// 删除帖子
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定删除该帖子吗？', '提示', {
      type: 'warning'
    })
    
    await request.delete(`/health/posts/${row.id}/`)
    ElMessage.success('删除成功')
    fetchPosts()
  } catch (error) {
    // 用户取消删除
  }
}

// 关闭编辑弹窗
const handleCloseEdit = () => {
  showEditModal.value = false
  postFormRef.value?.resetFields()
}

// 提交表单
const handleSubmit = async () => {
  if (!postFormRef.value) return
  
  try {
    const valid = await postFormRef.value.validate()
    if (!valid) return
    
    isSubmitting.value = true
    
    if (isAdd.value) {
      // 新增帖子
      await request.post('/health/posts/', postForm)
      ElMessage.success('发布成功')
    } else {
      // 更新帖子
      await request.put(`/health/posts/${postForm.id}/`, postForm)
      ElMessage.success('更新成功')
    }
    
    showEditModal.value = false
    fetchPosts()
  } catch (error: any) {
    ElMessage.error(error.message || '操作失败')
  } finally {
    isSubmitting.value = false
  }
}

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.current = 1
  fetchPosts()
}

const handleCurrentChange = (current: number) => {
  pagination.current = current
  fetchPosts()
}

onMounted(() => {
  fetchPosts()
})
</script>

<style scoped>
.user-posts {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-form {
  background: #f5f7fa;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>